<?php
	/**
	 * 文件缓存类
	 * 以后重写，太累了。
	 * @author cui lixin
	 *
	 */
	class file_cache extends base
	{
		/**
		 * 获取缓存
		 * Enter description here ...
		 * @param unknown_type $type
		 * @param unknown_type $key
		 * @param unknown_type $time
		 */
		public static function get($type, $key, $time)
		{
			$key = md5($key);
			$file_path = self::parse_file_name($type, $key);

			$content = self::include_file($file_path, $time);

			if (config::get()->cache->$type === FALSE)
			{
				return self::parse_data($content, 'get');
			}

			return $content;
		}

		/**
		 * 检查是否过期
		 * 返回文件路径
		 * @param unknown_type $type
		 * @param unknown_type $key
		 * @param unknown_type $time
		 */
		public static function is_expired($type, $key, $time = 86400)
		{
			$key = md5($key);
			$file_path = self::parse_file_name($type, $key);

			if (is_file($file_path) === FALSE)
			{
				return FALSE;
			}

			if (time_tools::$curr_time - filemtime($file_path) > $time)
			{
				return FALSE;
			}

			return $file_path;
		}

		/**
		 * 数据加密与解密
		 * Enter description here ...
		 * @param unknown_type $data
		 * @param unknown_type $type
		 * @return mixed|string
		 */
		private static function parse_data($data, $type = 'set')
		{
			if ($type == 'get')
			{
				return unserialize($data);
			}
			else
			{
				return serialize($data);
			}
		}

		/**
		 * 分析文件名
		 * Enter description here ...
		 * @param unknown_type $type
		 * @param unknown_type $key
		 */
		private static function parse_file_name($type, $key)
		{
			$file_path = DATA_PATH . 'cache' . DS . $type . DS;

			if (is_dir($file_path) === FALSE)
			{
				mkdir($file_path);
			}

			$file_path .= substr($key, 0, 2) . DS;

			if (is_dir($file_path) === FALSE)
			{
				mkdir($file_path);
			}

			return $file_path . $key;
		}

		/**
		 * 引入缓存文件
		 * Enter description here ...
		 * @param unknown_type $file_path
		 */
		private static function include_file($file_path, $time)
		{
			if (is_file($file_path) === FALSE)
			{
				return FALSE;
			}

			if ( time_tools::$curr_time - filemtime($file_path) > $time)
			{
				unlink($file_path);

				return FALSE;
			}

			return file_get_contents($file_path);
		}

		/**
		 * 设置缓存
		 * Enter description here ...
		 * @param unknown_type $type
		 * @param unknown_type $key
		 * @param unknown_type $value
		 */
		public static function set($type, $key, $value)
		{
			$key = md5($key);
			$file_path = self::parse_file_name($type, $key);

			self::save_cache($file_path, $value, $type);
		}

		/**
		 * 保存缓存文件
		 * Enter description here ...
		 * @param unknown_type $file_path
		 * @param unknown_type $value
		 */
		private static function save_cache($file_path, $value, $type)
		{
			if (empty($value))
			{
				return;
			}

			if (config::get()->cache->$type === FALSE)
			{
				$value = self::parse_data($value, 'set');
			}

			file_put_contents($file_path, $value);
		}
	}